<template>
  <Dialog
    v-model:visible="dialog.visible"
    modal
    :header="dialogTitle"
    @show="openHandler"
    @hide="closeHandler"
  >
    <el-form
      ref="dataForm"
      :rules="formRules"
      :model="entity"
      :disabled="operation == 3"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="parentId" label="上级部门">
            <dept-tree-select
              v-model="entity.parentId"
              placeholder="请选择上级部门"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="deptName" label="部门名称">
            <InputText v-model="entity.deptName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <cancel-button @click="dialog.visible = false" />
      <save-button
        v-if="operation != 3"
        :loading="loading"
        @click="saveHandler"
      />
    </template>
  </Dialog>
</template>
<script>
import { save, update } from '@/api/upms/dept'

export default {
  name: 'DeptEdit',
  props: {
    dialog: {
      type: Object,
      required: true,
    },
  },
  emits: ['success'],
  data() {
    return {
      loading: false,
      entity: {},
      formRules: {
        parentId: [
          { required: true, message: '请选择上级部门', trigger: 'blur' },
        ],
        deptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
        ],
      },
      titleMap: {
        1: '新建部门',
        2: '编辑部门',
        3: '查看部门',
      },
      depts: [],
    }
  },
  computed: {
    operation() {
      return this.dialog.operation
    },
    dialogTitle() {
      return this.titleMap[this.dialog.operation]
    },
  },
  methods: {
    openHandler() {
      this.entity = Object.assign({}, this.dialog.entity)
    },
    closeHandler() {
      this.entity = {}
    },
    saveHandler() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.loading = true
          let edit = this.operation == 1 ? save : update
          edit(this.entity)
            .then(() => {
              this.dialog.visible = false
              this.$message.success('保存成功')
              this.$emit('success')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
  },
}
</script>
